package com.dmooo.ymx.mall;

import android.content.Context;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import com.dmooo.ymx.R;
import com.dmooo.ymx.activity.MerchantAdminListActivity;
import com.dmooo.ymx.activity.MyMerchantAdminListActivity;
import com.dmooo.ymx.activity.ShopMallSearchResultActivity;
import com.dmooo.ymx.adapter.MyGridViewAdapter;
import com.dmooo.ymx.adapter.MyShopNewAdapter;
import com.dmooo.ymx.adapter.SearchHistoryNewAdapter;
import com.dmooo.ymx.base.BaseActivity;
import com.dmooo.ymx.bean.HaoDanBean;
import com.dmooo.ymx.bean.Response;
import com.dmooo.ymx.bean.SearchHistoryBean;
import com.dmooo.ymx.bean.TodayHighlightsBean2;
import com.dmooo.ymx.common.LogUtils;
import com.dmooo.ymx.common.SPUtils;
import com.dmooo.ymx.config.Constants;
import com.dmooo.ymx.fragments.HomeKindActivity;
import com.dmooo.ymx.https.HttpUtils;
import com.dmooo.ymx.https.onOKJsonHttpResponseHandler;
import com.dmooo.ymx.malladapter.ShopMallGoodsRecyclerAdapter;
import com.dmooo.ymx.mallbean.MallCatbean;
import com.dmooo.ymx.mallbean.ShopMallGoodsBean;
import com.dmooo.ymx.merchantadapter.HorizontalListViewAdapter;
import com.dmooo.ymx.merchantbean.MyMerchantlistbean;
import com.dmooo.ymx.utils.HorizontalListView;
import com.dmooo.ymx.utils.HorizontalListView1;
import com.dmooo.ymx.utils.MyRecyclerView2;
import com.dmooo.ymx.utils.StringUtils;
import com.dmooo.ymx.widget.CircleImageView;
import com.dmooo.ymx.widget.NoScrollGridView;
import com.dmooo.ymx.widget.indicator.MagicIndicator;
import com.dmooo.ymx.widget.indicator.ViewPagerHelper;
import com.dmooo.ymx.widget.indicator.buildins.UIUtil;
import com.dmooo.ymx.widget.indicator.buildins.commonnavigator.CommonNavigator;
import com.dmooo.ymx.widget.indicator.buildins.commonnavigator.abs.CommonNavigatorAdapter;
import com.dmooo.ymx.widget.indicator.buildins.commonnavigator.abs.IPagerIndicator;
import com.dmooo.ymx.widget.indicator.buildins.commonnavigator.abs.IPagerTitleView;
import com.dmooo.ymx.widget.indicator.buildins.commonnavigator.indicators.LinePagerIndicator;
import com.dmooo.ymx.widget.indicator.buildins.commonnavigator.titles.ClipPagerTitleView;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.loopj.android.http.RequestParams;
import com.loopj.android.http.TextHttpResponseHandler;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;
import com.zhy.adapter.recyclerview.wrapper.HeaderAndFooterWrapper;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cz.msebera.android.httpclient.Header;

/**
 * 官方旗舰店
 */
public class MyShopMallActivity extends BaseActivity {

    @BindView(R.id.tv_left)
    TextView tvLeft;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.tabBar)
    MagicIndicator tabBar;
    @BindView(R.id.viewpager)
    ViewPager viewpager;
    @BindView(R.id.tv_right)
    TextView tvRight;
    @BindView(R.id.mer_nameTv)
    TextView mer_nameTv;
    @BindView(R.id.img_all)
    ImageView img_all;
    @BindView(R.id.imgs)
    CircleImageView imgs;
    @BindView(R.id.chat_tv)
    TextView chat_tv;
    @BindView(R.id.horizontal_lv)
    HorizontalScrollView horizontal_lv;
//    @BindView(R.id.grid_view)
//    GridView searchgridView;

//    @BindView(R.id.home_recyclerView)
//    RecyclerView homeRecyclerView;

    @BindView(R.id.merchanthome_typerecy)
    MyRecyclerView2 typerecy;
    @BindView(R.id.server_details_content_view_product_gv)
    GridView mygridView;

    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.recyclerViewall)
    RecyclerView recyclerViewall;


    @BindView(R.id.refresh_layout)
    SmartRefreshLayout refreshLayout;

    List<MallCatbean> horListlist;

    private MyShopNewAdapter myShopNewAdapter;

    private String min_id = "1";
    private int index;
    private boolean hasdata = true;
    private List<Fragment> fragments = new ArrayList<>();


    private int page = 1;
    private HorizontalListViewAdapter merchanthomeAdapter;
    private HeaderAndFooterWrapper headerAndFooterWrapper;
    private ShopMallGoodsRecyclerAdapter shopRecyclerAdapter;
    private ShopMallGoodsRecyclerAdapter shopRecyclerAdapterAll;
    private NoScrollGridView gridView;
    private NoScrollGridView gridViewAll;
    private SearchHistoryNewAdapter searchHistoryAdapter;
    List<SearchHistoryBean> historyBeans = new ArrayList<>();

    @BindView(R.id.search_lv_tips)
    ListView searchLvTips;
    private List<String> searchTips=new ArrayList<>();
    private ArrayAdapter searchAdapter;
    private int indexNum = 1;
    private int status = 0;


    @Override
    protected void initUI() {
        setContentView(R.layout.activity_myshop);
        ButterKnife.bind(this);
    }

    @Override
    protected void initData() {
        tvLeft.setVisibility(View.VISIBLE);
        tvRight.setVisibility(View.GONE);
        tvRight.setText("购物车");
        tvRight.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                openActivity(MallGoodsCartActivity.class);
            }
        });
        gridView = new NoScrollGridView(this);
        gridView.setNumColumns(4);
        gridView.setGravity(Gravity.CENTER);
        gridView.setBackgroundColor(this.getResources().getColor(R.color.white));
        RecyclerView.LayoutParams layoutParams = new RecyclerView.LayoutParams(RecyclerView.LayoutParams.MATCH_PARENT, RecyclerView.LayoutParams.WRAP_CONTENT);
        layoutParams.setMargins(0, 0, 0, UIUtil.dip2px(this, 3));
        layoutParams.width = RecyclerView.LayoutParams.MATCH_PARENT;
        layoutParams.height = RecyclerView.LayoutParams.WRAP_CONTENT;
        gridView.setLayoutParams(layoutParams);

        gridViewAll = new NoScrollGridView(this);
        gridViewAll.setNumColumns(4);
        gridViewAll.setGravity(Gravity.CENTER);
        gridViewAll.setBackgroundColor(this.getResources().getColor(R.color.white));
        RecyclerView.LayoutParams layoutParamsAll = new RecyclerView.LayoutParams(RecyclerView.LayoutParams.MATCH_PARENT, RecyclerView.LayoutParams.WRAP_CONTENT);
        layoutParamsAll.setMargins(0, 0, 0, UIUtil.dip2px(this, 0));
        layoutParamsAll.width = RecyclerView.LayoutParams.MATCH_PARENT;
        layoutParamsAll.height = RecyclerView.LayoutParams.WRAP_CONTENT;
        gridViewAll.setLayoutParams(layoutParamsAll);

//        mygridView=new GridView(this);

        searchHistoryAdapter = new SearchHistoryNewAdapter(this);
        searchHistoryAdapter.setData(historyBeans);



        shopRecyclerAdapterAll = new ShopMallGoodsRecyclerAdapter(MyShopMallActivity.this, R.layout.shop_mall_goods_item, taobaoGuesChildtBeansAll);
        recyclerViewall.setLayoutManager(new GridLayoutManager(MyShopMallActivity.this, 2));
        headerAndFooterWrapper = new HeaderAndFooterWrapper(shopRecyclerAdapterAll);
        headerAndFooterWrapper.addHeaderView(gridViewAll);
        recyclerViewall.setAdapter(headerAndFooterWrapper);



        getmerchantlist();
    }

    @Override
    protected void initListener() {
        refreshLayout.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                status = 0;
                if (hasdata) {
                    indexNum++;
                    try{
                        if(getIntent().getStringExtra("mer_id")!=null){
                            getTbkListRequstAll(getIntent().getStringExtra("mer_id"));
                        }else{
                            getTbkListRequstAll(merchantlistbeans.get(0).merchant_id);
                        }
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                } else {
                    showToast("没有更多数据了");
                    refreshLayout.finishLoadMore(2000);
                }
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                hasdata = true;
                status = 1;
                indexNum = 1;
                if(getIntent().getStringExtra("mer_id")!=null){
                    getTbkListRequstAll(getIntent().getStringExtra("mer_id"));
                }else{
                    getTbkListRequstAll(merchantlistbeans.get(0).merchant_id);
                }
            }
        });

        mygridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                Bundle bundle=new Bundle();
                bundle.putString("name",horListlist.get(position).cat_name);
                bundle.putString("pid",horListlist.get(position).cat_id);
                openActivity(ShopMallActivty.class,bundle);
            }
        });
        img_all.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                openActivity(HomeKindActivity.class);
            }
        });
        tvTitle.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (!TextUtils.isEmpty(StringUtils.doViewToString(tvTitle))) {
                    ((InputMethodManager) tvTitle.getContext().getSystemService(Context.INPUT_METHOD_SERVICE))
                            .hideSoftInputFromWindow(
                                    getComeActivity()
                                            .getCurrentFocus()
                                            .getWindowToken(),
                                    InputMethodManager.HIDE_NOT_ALWAYS);
                    //存储历史
                    SearchHistoryBean searchHistoryBean = new SearchHistoryBean();
                    searchHistoryBean.setContent(StringUtils.doViewToString(tvTitle));
                    if (!historyBeans.contains(searchHistoryBean)) {
//                        historyBeans.add(searchHistoryBean);
//                        searchHistoryAdapter.setData(historyBeans);
//                        gridView.setAdapter(searchHistoryAdapter);
                    }
                    Bundle bundle = new Bundle();
                    bundle.putString("content", StringUtils.doViewToString(tvTitle));
                    bundle.putInt("type", 0);//1高级搜索 0 普通搜索
                    openActivity(ShopMallSearchResultActivity.class, bundle);
                } else {
                    showToast("你未输入搜索内容");
                }
                return false;
            }
        });
        tvTitle.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if(s.toString().equals("")){
                    searchLvTips.setVisibility(View.GONE);
                }else{
                    searchLvTips.setVisibility(View.VISIBLE);
                    getTip();
                }
            }
        });
        searchAdapter=new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, searchTips);
        searchLvTips.setAdapter(searchAdapter);
        searchLvTips.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                //存储历史
                SearchHistoryBean searchHistoryBean = new SearchHistoryBean();
                searchHistoryBean.setContent(StringUtils.doViewToString(tvTitle));
                Bundle bundle = new Bundle();
                bundle.putString("content", searchTips.get(position));
                bundle.putInt("type", 0);//1高级搜索 0 普通搜索
                openActivity(ShopMallSearchResultActivity.class, bundle);
            }
        });

        chat_tv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Bundle bundle=new Bundle();
                bundle.putString("merchant_id",merchantlistbeans.get(0).merchant_id);
                bundle.putString("type","2");
                bundle.putString("image","");
                bundle.putString("msg","你好，我想咨询服务:");
                openActivity(MyMerchantAdminListActivity.class,bundle);
//                showCallDialog("",merchantlistbeans.get(0).service_tel);
            }
        });

    }

    /**
     * 获取相关搜索
     */
    private void getTip(){
        RequestParams requestParams = new RequestParams();
        HttpUtils.post("https://suggest.taobao.com/sug?&code=utf-8&q="+tvTitle.getText().toString().replace(" ","")+"&callback=jQuery22408778692875219454_1542943610945&_=1542943610950&qq-pf-to=pcqq.group", requestParams, new TextHttpResponseHandler() {
            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                LogUtils.d("dsfasd",responseString);
            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, String responseString) {
                String str=responseString.replace("jQuery22408778692875219454_1542943610945(","");
                str=str.substring(0,str.length()-1);
                try {
                    JSONObject object=new JSONObject(str);
                    JSONArray array=object.getJSONArray("result");
                    searchTips.clear();
                    for(int i=0;i<array.length();i++){
                        JSONArray array1=array.getJSONArray(i);
                        searchTips.add(array1.getString(0));
                    }
                    searchAdapter.notifyDataSetChanged();
                } catch (JSONException e) {
                    e.printStackTrace();
                    searchLvTips.setVisibility(View.GONE);
                }
            }
        });
    }

    @OnClick(R.id.tv_left)
    public void onViewClicked() {
        finish();
    }

    /**
     * @属性:获取顶级淘宝商品分类列表
     * @开发者:陈飞
     * @时间:2018/7/26 15:31
     */
    private void getTopCatListRequst() {
        RequestParams requestParams = new RequestParams();
        requestParams.put("merchant_id",merchantlistbeans.get(0).merchant_id);
        HttpUtils.post(Constants.APP_IP+"/app.php?c=GoodsCat&a=getCatByMerchant", requestParams, new onOKJsonHttpResponseHandler<MallCatbean>(new TypeToken<Response<MallCatbean>>() {
        }) {
            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                showToast(responseString);
            }

            @Override
            public void onStart() {
                super.onStart();
            }

            @Override
            public void onFinish() {
                super.onFinish();
            }

            @Override
            public void onSuccess(int statusCode, Response<MallCatbean> datas) {
                if (datas.isSuccess()) {
                    horListlist=new ArrayList<>();
                    horListlist = datas.getData().list;

//                    horListlist=new ArrayList<>();
//                    horListlist = datas.getData().list;
//                    merchanthomeAdapter = new HorizontalListViewAdapter(MyShopMallActivity.this,horListlist);
//                    horizontal_lv.setAdapter(merchanthomeAdapter);
//                    merchanthomeAdapter.notifyDataSetChanged();
                    setGridView();
                } else {
                    showToast(datas.getMsg());
                }
            }
        });
    }

    private void setGridView() {
        int size = horListlist.size();
        int length = 100;
        DisplayMetrics dm = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm);
        float density = dm.density;
        int gridviewWidth = (int) (size * (length + 4) * density);
        int itemWidth = (int) (length * density);

        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                gridviewWidth, LinearLayout.LayoutParams.FILL_PARENT);
        mygridView.setLayoutParams(params); // 设置GirdView布局参数,横向布局的关键
        mygridView.setColumnWidth(itemWidth); // 设置列表项宽
        mygridView.setHorizontalSpacing(2); // 设置列表项水平间距
        mygridView.setStretchMode(GridView.NO_STRETCH);
        mygridView.setNumColumns(size); // 设置列数量=列表集合数

        MyGridViewAdapter adapter = new MyGridViewAdapter(getApplicationContext(),
                horListlist);
        mygridView.setAdapter(adapter);
    }
    /**
     * 获取商户列表  源曦默官方旗舰店
     */
    public List<MyMerchantlistbean> merchantlistbeans = new ArrayList<>();
    private void getmerchantlist() {
        RequestParams requestParams = new RequestParams();
        HttpUtils.post(Constants.getMerchantList, requestParams, new TextHttpResponseHandler() {
            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                Log.d("dsfasd", responseString);
            }
            @Override
            public void onSuccess(int statusCode, Header[] headers, String responseString) {
                try {
                    JSONObject object = new JSONObject(responseString);
                    if ("0".equals(object.getString("code"))) {
                        JSONArray array = object.getJSONObject("data").getJSONArray("list");
                        if(page==1){
                            merchantlistbeans.clear();
                        }
                        for (int i = 0; i < array.length(); i++) {
                            merchantlistbeans.add(new Gson().fromJson(array.getJSONObject(i).toString(), MyMerchantlistbean.class));
                        }
                        try{
                            if(getIntent().getStringExtra("mer_id")!=null){
                                if(getIntent().getStringExtra("mer_name")==null){
                                    mer_nameTv.setText(merchantlistbeans.get(0).merchant_name);
                                }else{
                                    mer_nameTv.setText(getIntent().getStringExtra("mer_name"));
                                }
//                                Glide.with(MyShopMallActivity.this).load(Constants.APP_IP+merchantlistbeans.get(0).merchant_avatar).into(imgs);
//                                getTbkListRequst(getIntent().getStringExtra("mer_id"));
                                getTbkListRequstAll(getIntent().getStringExtra("mer_id"));
                            }else{
                                mer_nameTv.setText(merchantlistbeans.get(0).merchant_name);
//                                getTbkListRequst(merchantlistbeans.get(0).merchant_id);
                                getTbkListRequstAll(merchantlistbeans.get(0).merchant_id);
                            }
                            Glide.with(MyShopMallActivity.this).load(Constants.APP_IP+merchantlistbeans.get(0).merchant_avatar).into(imgs);
                        }catch (Exception e){
                            e.printStackTrace();
                        }
                        getTopCatListRequst();
                    } else {
                        showToast(object.getString("msg"));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * 获取特价商品
     */
    List<ShopMallGoodsBean> taobaoGuesChildtBeans = new ArrayList<>();
    private void getTbkListRequst(String merid) {
        RequestParams requestParams = new RequestParams();
        requestParams.put("p", 1);
        requestParams.put("merchant_id", merid);
        requestParams.put("per", 3);
//        requestParams.put("is_sale", "Y");
        Log.d("ddddd",merid);
        HttpUtils.post(Constants.SLEF_MALL_GOODS, requestParams, new onOKJsonHttpResponseHandler<ShopMallGoodsBean>(new TypeToken<Response<ShopMallGoodsBean>>() {
        }) {
            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                showToast(responseString);
            }

            @Override
            public void onSuccess(int statusCode, Response<ShopMallGoodsBean> datas) {
                if (datas.isSuccess()) {
                    List<ShopMallGoodsBean> list = datas.getData().list;
                    taobaoGuesChildtBeans.clear();
                    taobaoGuesChildtBeans.addAll(list);
                    if (list.size() <= 0) {
                        hasdata = false;
                    }
                } else {
                    showToast(datas.getMsg());
                }
                shopRecyclerAdapter = new ShopMallGoodsRecyclerAdapter(MyShopMallActivity.this, R.layout.my_shop_mall_goods_item, taobaoGuesChildtBeans);
                recyclerView.setLayoutManager(new GridLayoutManager(MyShopMallActivity.this, 3));
                headerAndFooterWrapper = new HeaderAndFooterWrapper(shopRecyclerAdapter);
                headerAndFooterWrapper.addHeaderView(gridView);
                recyclerView.setAdapter(headerAndFooterWrapper);
                headerAndFooterWrapper.notifyDataSetChanged();
            }
        });
    }

    /**
     * 获取全部商品
     */
    List<ShopMallGoodsBean> taobaoGuesChildtBeansAll = new ArrayList<>();
    private void getTbkListRequstAll(String merid) {
        RequestParams requestParams = new RequestParams();
        requestParams.put("p", indexNum);
        requestParams.put("merchant_id", merid);
        requestParams.put("per", 10);
        Log.d("ddddd",merid);
        HttpUtils.post(Constants.SLEF_MALL_GOODS, requestParams, new onOKJsonHttpResponseHandler<ShopMallGoodsBean>(new TypeToken<Response<ShopMallGoodsBean>>() {
        }) {
            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                showToast(responseString);
            }

            @Override
            public void onSuccess(int statusCode, Response<ShopMallGoodsBean> datas) {
                if (datas.isSuccess()) {
                    if (status == 1) {
                        taobaoGuesChildtBeansAll.clear();
                    }
                    List<ShopMallGoodsBean> list = datas.getData().list;
                    taobaoGuesChildtBeansAll.addAll(list);
                    if (list.size() <= 0) {
                        hasdata = false;
                    }
                } else {
                    showToast(datas.getMsg());
                }
                if (refreshLayout != null) {
                    if (status == 1) {
                        refreshLayout.finishRefresh();
                    } else {
                        refreshLayout.finishLoadMore();
                    }
                }
                headerAndFooterWrapper.notifyDataSetChanged();
            }
        });
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }
}

